package mi.payment.transaction.refund;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.DatePicker;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import lainey.ui.dialog.DateDialog;
import lainey.ui.dialog.EditTextDialog;
import lainey.ui.dialog.ListDialog;
import lainey.ui.widget.TitleView;
import mi.payment.R;
import mi.payment.bean.db.TradeData;
import mi.payment.constants.AccountType;
import mi.payment.constants.Configs;
import mi.payment.constants.Params;
import mi.payment.db.dao.PayDetail;
import mi.payment.settings.TransactionOtherOperation;
import mi.payment.transaction.AutoFinishActivity;
import mi.payment.ui.base.PageRoute;
import mi.payment.ui.other.OnlyInputAmountActivity;
import mi.payment.utils.MoneyUtils;
import mi.payment.utils.transaction.QRCodeReturnGoodsTask;
import sunmi.payment.L3.L3BroadcastHelper;
import sunmi.payment.L3.L3ErrorCode;
import sunmi.payment.L3.L3Params;
import sunmi.payment.ui.dialog.LoadDialog;

/**
 * 退货模块 -- 二维码输入信息界面
 */
public class QRCodeReturnGoodsActivity extends AutoFinishActivity {

    private static final String EXTRA_PAY_TYPE = "extra_pay_type";
    private static final String EXTRA_ORDER_NUM = "extra_order_num";

    private long mAmount;
    private int mPayType = 1;
    private int mChannelType;

    private TextView mTvDate;
    private TextView mTvAmount;
    private TextView mTvOrderNo;
    private TextView mTvPayType;

    private TradeData mTradeData;
    private PayDetail mPayDetail;

    private ListDialog mListDialog;
    private DateDialog mDateDialog;
    private EditTextDialog mEditTextDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.transaction_refund_activity_input_info);
        initView();
        fillData();
    }

    private void initView() {
        String orderNo = getIntent().getStringExtra(EXTRA_ORDER_NUM);
        mChannelType = getIntent().getIntExtra(EXTRA_PAY_TYPE, -1);

        mTradeData = Params.getTradeData();
        mPayDetail = mTradeData.getPayDetail();
        mPayDetail.accountType = AccountType.OA.getValue();

        TitleView titleView = findViewById(R.id.title_view);
        titleView.setCenterText(R.string.refund);
        titleView.setLeftImageOnClickListener(
                v -> onBackPressed()
        );

        View item = findViewById(R.id.item_channel);
        item.findViewById(R.id.left_image).setVisibility(View.GONE);
        item.findViewById(R.id.right_image).setVisibility(View.GONE);
        TextView leftText = item.findViewById(R.id.left_text);
        leftText.setText(R.string.transaction_original_pay_channel);
        TextView rightText = item.findViewById(R.id.right_text);
        switch (mChannelType) {
            case 1:
                rightText.setText(R.string.platform_ali);
                break;
            case 2:
                rightText.setText(R.string.platform_wx);
                break;
            case 3:
                rightText.setText(R.string.platform_union);
                break;
            default:
                rightText.setText(R.string.platform_code);
                break;
        }

        item = findViewById(R.id.item_type);
        item.findViewById(R.id.left_image).setVisibility(View.GONE);
        leftText = item.findViewById(R.id.left_text);
        leftText.setText(R.string.transaction_original_type);
        mTvPayType = item.findViewById(R.id.right_text);
        item.setOnClickListener(this);
        if (mPayType == 0) {
            mTvPayType.setText(R.string.unfilled);
        } else {
            mTvPayType.setText(R.string.platform_scan_merchant);
        }

        item = findViewById(R.id.item_order_number);
        item.findViewById(R.id.left_image).setVisibility(View.GONE);
        leftText = item.findViewById(R.id.left_text);
        leftText.setText(R.string.transaction_original_reference_number);
        mTvOrderNo = item.findViewById(R.id.right_text);
        item.setOnClickListener(this);
        if (orderNo != null && orderNo.length() > 0) {
            mTvOrderNo.setText(orderNo);
        } else {
            mTvOrderNo.setText(R.string.unfilled);
        }

        item = findViewById(R.id.item_date);
        item.findViewById(R.id.left_image).setVisibility(View.GONE);
        leftText = item.findViewById(R.id.left_text);
        leftText.setText(R.string.transaction_original_date);
        mTvDate = item.findViewById(R.id.right_text);
        mTvDate.setText(R.string.unfilled);
        item.setOnClickListener(this);
        // 退货 - 二维码退货是否输入原交易日期
        if (Configs.isRefundInputOriginalDate) {
            item.setVisibility(View.VISIBLE);
        } else {
            item.setVisibility(View.GONE);
        }

        item = findViewById(R.id.item_amount);
        item.findViewById(R.id.left_image).setVisibility(View.GONE);
        leftText = item.findViewById(R.id.left_text);
        leftText.setText(R.string.money);
        mTvAmount = item.findViewById(R.id.right_text);
        mTvAmount.setText(R.string.unfilled);
        item.setOnClickListener(this);
        // 退货 - 二维码退货是否输入原交易金额
        if (Configs.isRefundInputOriginalAmount) {
            item.setVisibility(View.VISIBLE);
        } else {
            item.setVisibility(View.GONE);
        }

        findViewById(R.id.mb_ok).setOnClickListener(this);
    }

    private void fillData() {
        try {
            L3Params l3Params = Params.sL3Params;
            if (l3Params == null) return;
            // 如果L3过来，带有参考号、日期则填入
            String orderNo = l3Params.oriQROrderNo;
            if (orderNo != null && orderNo.length() > 0) {
                mTvOrderNo.setText(orderNo);
            }

            if (l3Params.amount > 0 && l3Params.amount <= 999999999) {
                mAmount = l3Params.amount;
                String money = MoneyUtils.longCent2DoubleMoneyStr(l3Params.amount);
                String temp = getString(R.string.money_only_symbol) + money;
                mTvAmount.setText(temp);
            }

            String date = l3Params.oriTransDate;
            if (date == null || date.length() < 4) return;
            if (date.length() == 4) {
                String temp = date.substring(0, 2) + "/" + date.substring(2, 4);
                mTvDate.setText(temp);
            } else if (date.length() == 8) {
                String temp = date.substring(4, 6) + "/" + date.substring(6, 8);
                mTvDate.setText(temp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        L3BroadcastHelper.sendFailedBroadcast(mContext, L3ErrorCode.ERROR_TRADE_CANCEL);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dismissDateDialog();
        dismissListDialog();
        dismissEditTextDialog();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null && resultCode == OnlyInputAmountActivity.RESULT_CODE) {
            String value = data.getStringExtra(OnlyInputAmountActivity.RESULT_AMOUNT);
            if (value != null && value.trim().length() > 0) {
                mAmount = MoneyUtils.stringMoney2LongCent(value);
                String str = getString(R.string.money_only_symbol) + value;
                mTvAmount.setText(str);
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void onClick(View v) {
        final int id = v.getId();
        switch (id) {
            case R.id.item_type:
                showListDialog();
                break;
            case R.id.item_order_number:
                showEditTextDialog();
                break;
            case R.id.item_date:
                showDateDialog();
                break;
            case R.id.item_amount:
                Intent intent = new Intent(this, OnlyInputAmountActivity.class);
                startActivityForResult(intent, OnlyInputAmountActivity.RESULT_CODE);
                break;
            case R.id.mb_ok:
                qrCodeRefund();
                break;
        }
    }

    private void showListDialog() {
        if (mListDialog == null) {
            mListDialog = new ListDialog(this);
            mListDialog.setTitleText(R.string.transaction_please_select_pay_type);
            mListDialog.setCancelable(true);
            mListDialog.setCanceledOnTouchOutside(true);
            String[] data = {
                    getString(R.string.platform_scan_merchant),
                    getString(R.string.platform_scan_customer),
            };
            mListDialog.setData(data);
            mListDialog.setOnItemClickListener(
                    position -> {
                        switch (position) {
                            case 0:
                                mPayType = 1;
                                mTvPayType.setText(R.string.platform_scan_merchant);
                                break;
                            case 1:
                                mPayType = 2;
                                mTvPayType.setText(R.string.platform_scan_customer);
                                break;
                            default:
                                mPayType = 0;
                                mTvPayType.setText(R.string.platform_scan_merchant);
                                break;
                        }
                    }
            );
        }
        try {
            mListDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showEditTextDialog() {
        if (mEditTextDialog == null) {
            mEditTextDialog = new EditTextDialog(this);
            mEditTextDialog.setRightText(R.string.ui_ok);
            mEditTextDialog.setLeftText(R.string.ui_cancel);
            mEditTextDialog.setTitleText(R.string.transaction_please_input_original_reference_number);
            mEditTextDialog.setCancelable(true);
            mEditTextDialog.setCanceledOnTouchOutside(true);
            mEditTextDialog.setTextMode();
            mEditTextDialog.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
            mEditTextDialog.setLeftOnClickListener(
                    v -> dismissEditTextDialog()
            );
            mEditTextDialog.setRightOnClickListener(
                    v -> {
                        String text = mEditTextDialog.getText();
                        if (text.trim().length() > 0) {
                            mTvOrderNo.setText(text);
                            dismissEditTextDialog();
                        } else {
                            showToast(R.string.error_input_reference_number_hint);
                        }
                    }
            );
        }
        String orderId = mTvOrderNo.getText().toString();
        boolean equals = TextUtils.equals(getString(R.string.unfilled), orderId);
        if (equals) {
            mEditTextDialog.setText("");
        } else {
            mEditTextDialog.setText(orderId);
        }
        try {
            mEditTextDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showDateDialog() {
        if (mDateDialog == null) {
            mDateDialog = new DateDialog(this);
            mDateDialog.setRightText(R.string.ui_ok);
            mDateDialog.setLeftText(R.string.ui_cancel);
            mDateDialog.setTitleText(R.string.transaction_please_input_original_date);
            mDateDialog.setCancelable(true);
            mDateDialog.setCanceledOnTouchOutside(true);
            mDateDialog.setLeftOnClickListener(
                    v -> dismissDateDialog()
            );
            mDateDialog.setRightOnClickListener(
                    v -> {
                        DatePicker datePicker = mDateDialog.getDatePicker();
                        int year = datePicker.getYear();
                        int month = datePicker.getMonth();
                        int dayOfMonth = datePicker.getDayOfMonth();
                        Calendar calendar = Calendar.getInstance();
                        calendar.set(year, month, dayOfMonth);
                        // 将当前时间进行格式化
                        Date time = calendar.getTime();
                        String date = new SimpleDateFormat("MM/dd").format(time);
                        mTvDate.setText(date);
                        dismissDateDialog();
                    }
            );
            int color = getResources().getColor(R.color.colorPrimary);
            mDateDialog.setDatePickerDividerColor(color);
        }
        try {
            mDateDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void dismissListDialog() {
        if (mListDialog != null) {
            mListDialog.dismiss();
        }
    }

    private void dismissDateDialog() {
        if (mDateDialog != null) {
            mDateDialog.dismiss();
        }
    }

    private void dismissEditTextDialog() {
        if (mEditTextDialog != null) {
            mEditTextDialog.dismiss();
        }
    }

    private void qrCodeRefund() {
        String orderNo = mTvOrderNo.getText().toString();
        boolean equals = TextUtils.equals(getString(R.string.unfilled), orderNo);
        if (equals) {
            showToast(R.string.error_input_order_number_hint);
            return;
        }

        String date = mTvDate.getText().toString();
        if (date.trim().length() < 4) {
            showToast(R.string.error_input_date_hint);
            return;
        }

        // 金额
        if (mAmount == 0) {
            showToast(R.string.error_input_amount_hint);
            return;
        }
        long maxAmount = TransactionOtherOperation.getInstance().getTransactionOtherSettings().getMaximumReturnAmount();
        if (mAmount > maxAmount) {
            showToast(R.string.error_input_amount_over);
            return;
        }

        switch (mChannelType) {
            case 1:
                mPayDetail.transPlatform = 1;
                break;
            case 2:
                mPayDetail.transPlatform = 2;
                break;
            case 3:
                mPayDetail.transPlatform = 4;
                break;
            default:
                mPayDetail.transPlatform = 1;
                break;
        }

        mPayDetail.amount = mAmount;
        mPayDetail.qrCodeScanModel = mPayType;
        // 原交易日期
        date = date.trim().replaceAll("/", "");
        mPayDetail.originalTransDate = date;
        mPayDetail.thirdTransNum = orderNo;

        // L3自定义订单号赋值
        L3Params l3Params = Params.sL3Params;
        if (l3Params != null) {
            mPayDetail.customOrderNo = l3Params.transId;
        }
        mTradeData.setPayDetail(mPayDetail);

        // 退货
        mTradeData.getPayDetail().setTransactionType(3);
        @SuppressLint("StaticFieldLeak")
        QRCodeReturnGoodsTask task = new QRCodeReturnGoodsTask(mContext) {

            @Override
            protected void onPostExecuteImpl(TradeData tradeData) {
                PayDetail resPay = tradeData.getPayDetail();
                PageRoute.startAction(mActivity, PageRoute.TYPE_QR_CODE_RETURN_GOOD, resPay);
            }

            @Override
            protected void onTaskTimeoutImpl() {
                PageRoute.startTimeoutAction(mActivity, PageRoute.TYPE_QR_CODE_RETURN_GOOD, mTradeData.payDetail);
            }

        };
        LoadDialog dialog = getLoadingDialog(R.string.load_connecting);
        task.setLoadDialog(dialog);
        task.execute(mTradeData);
    }

    public static void startAction(Context context, int type, String data) {
        Intent intent = new Intent(context, QRCodeReturnGoodsActivity.class);
        intent.putExtra(QRCodeReturnGoodsActivity.EXTRA_ORDER_NUM, data);
        intent.putExtra(QRCodeReturnGoodsActivity.EXTRA_PAY_TYPE, type);
        context.startActivity(intent);
    }


}
